package com.dx.intercepter;
// TODO jwt拦截器待完善
//class JwtIntercepter {
//}

import cn.hutool.core.bean.BeanUtil;
import com.dx.constants.Constants;
import com.dx.context.ContextHolder;
import com.dx.entity.bo.Employee;
import com.dx.exception.PermissionVerifyException;
import com.dx.properties.JwtProperties;
import com.dx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
@RequiredArgsConstructor
public class JwtIntercepter implements HandlerInterceptor {
    private final JwtProperties jwtProperties;
    private final RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        log.info(" 进入jwt拦截器 ");
        //TODO jwt解析过程中碰到异常如何处理
        //Answer 目前是在里面加了异常处理，抛出异常。
        //1. jwtToken为空
        //2. jwtToken过期

        System.out.println("Thread.currentThread().getId() = " + Thread.currentThread().getId());
        String jwtToken = request.getHeader(Constants.tokenName);
        if (jwtToken==null) {
            throw new PermissionVerifyException("sa-token不能为空值");
        }
        Claims claims = JwtUtil.parseToken(jwtToken,jwtProperties.getSecretKey());
        String uuid= claims.get(Constants.uuId).toString();

        if (redisTemplate.opsForValue().get(uuid)==null) {
            throw new RuntimeException("用户登录超时");
        }
        System.out.println("redisTemplate.opsForValue().get(uuid) = " + redisTemplate.opsForValue().get(uuid));
        Employee employee = BeanUtil.copyProperties(redisTemplate.opsForValue().get(uuid),Employee.class);
        ContextHolder.setUser(employee);
        ContextHolder.setJwtToken(jwtToken);
        final Employee user = ContextHolder.getUser();
        System.out.println("user = " + user);
        return true;

    }
}
